/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TMS;
import java.util.Scanner;
import java.io.*;
import java.rmi.AccessException;
/**
 *
 * @author Zachary
 */
public class Storage_Device {
    private static String Path = "C:\\TMS\\" ;
    private static String USER_LIST = "TMS_USER_LIST.txt";
public static void new_profile(User_Profile profile) throws FileNotFoundException, IOException{
        File access_list = new File(Path + USER_LIST);
        String entry_name = ""; String entry_pin = "";
        boolean user_exists = false;
        /* Check Access List For entry */
        if (access_list.exists() == false) {
            access_list.createNewFile();
        }
        if (access_list.length() > 0){
            FileReader file_reader = new FileReader(access_list);
            Scanner file_scanner = new Scanner(file_reader);
            /* Scan each entry until the desired user entry is found */

            while (file_scanner.hasNextLine()){
                Scanner line_scanner = new Scanner(file_scanner.nextLine());
                line_scanner.useDelimiter(",");
                //Get name and pin from access list
                entry_name = line_scanner.next();
                entry_pin = line_scanner.next();
                /* If the desired user has been found */
                if (entry_name.equalsIgnoreCase(profile.get_user_name())){
                    user_exists = true;
                    break;
                }
            }
            //Close File
            file_reader.close();
        }
        /* If an entry exists, check the pin and modify the user's data */
        if (!user_exists){
            /* Append a new entry to the user list */
            FileWriter file_writer = new FileWriter(Path + USER_LIST, true);
            file_writer.append(profile.get_user_name() + "," + profile.get_user_pin() + System.getProperty("line.separator"));
            file_writer.close();
            /* Create a new user file and store the user's data */
            store_profile(profile);
        }
        /* Otherwise, the user exists but the pin is incorrect */
        else{
            throw new AccessException("No such user with the given pin exists.");
        }
    }
    
    public static void save_profile(User_Profile profile) throws FileNotFoundException, IOException{
        File access_list = new File(Path + USER_LIST);
        String entry_name = ""; String entry_pin = "";
        boolean user_exists = false;
        /* Check Access List For entry */
        if (access_list.exists() == false) {
            access_list.createNewFile();
        }
        if (access_list.length() > 0){
            FileReader file_reader = new FileReader(access_list);
            Scanner file_scanner = new Scanner(file_reader);
            /* Scan each entry until the desired user entry is found */
            
            while (file_scanner.hasNextLine()){
                Scanner line_scanner = new Scanner(file_scanner.nextLine());
                line_scanner.useDelimiter(",");
                //Get name and pin from access list
                entry_name = line_scanner.next();
                entry_pin = line_scanner.next();
                /* If the desired user has been found */
                if (entry_name.equalsIgnoreCase(profile.get_user_name())){
                    user_exists = true;
                    break;
                }
            }
            //Close File
            file_reader.close();
        }
        /* If an entry exists, check the pin and modify the user's data */
        if (user_exists && (new Integer(entry_pin) == profile.get_user_pin())){
            store_profile(profile);
        }
        /* If the entry does not exist, make the entry and save the user's data */
        else if (!user_exists){
            /* Append a new entry to the user list */
            FileWriter file_writer = new FileWriter(Path + USER_LIST, true);
            file_writer.append(profile.get_user_name() + "," + profile.get_user_pin() + System.getProperty("line.separator"));
            file_writer.close();
            /* Create a new user file and store the user's data */
            store_profile(profile);
        }
        /* Otherwise, the user exists but the pin is incorrect */
        else{
            throw new AccessException("No such user with the given pin exists.");
        }
    }
    public static User_Profile get_profile(String user_name, int user_pin) throws FileNotFoundException, IOException{
        File access_list = new File(Path + USER_LIST);
        /* If access_list exists and has at least one entry then */
        if (access_list.exists() && access_list.length() > 0){

            FileReader file_reader = new FileReader(access_list);
            Scanner file_scanner = new Scanner(file_reader);
            /* Scann each entry until the desired user entry is found */
            while (file_scanner.hasNextLine()){
                Scanner line_scanner = new Scanner(file_scanner.nextLine());
                line_scanner.useDelimiter(",");
                //Get name and pin from access list
                String entry_name = line_scanner.next();
                String entry_pin = line_scanner.next();
                /* If the desired user has been found */
                if (entry_name.equalsIgnoreCase(user_name)){
                    Integer test_pin = new Integer(entry_pin);
                    /* Check the user pin against the stored pin */
                    if (test_pin == user_pin){
                        //Load Profile
                        User_Profile rv = load_profile(entry_name);
                        rv.set_logged_in(true);
                        //Close File
                        file_reader.close();
                        //Return output
                        return rv;
                    }
                }
            }
            //Close File
            file_reader.close();
        }
        return new User_Profile();
    }
    //Private Helper Functions
    private static void store_profile(User_Profile profile) throws IOException{
        File user_file = new File(Path + profile.get_user_name());
        FileWriter file_writer = new FileWriter(user_file);
        /* Write User Name and Pin */
        file_writer.write(profile.get_user_name() + ",");
        file_writer.write(profile.get_user_pin() + ",");
        /* Write Session Count*/
        file_writer.write(String.valueOf(profile.get_session_count()));
        /* Write Sessions */
        for (int i = 0; i < profile.get_session_count();i++){
            workout_session iSession= profile.get_session(i);
            file_writer.write(System.getProperty("line.separator"));
            /* Write Session Time */
            file_writer.write(iSession.session_time + ",");
            /* Write Distance Run */
            file_writer.write(iSession.distance_run + ",");
            /* Write Average Heartrate */
            file_writer.write(iSession.heartrate_average + ",");
            /* Write Calories Burned */
            file_writer.write(iSession.calories_burned + ",");
            /* Write Current Weight */
            file_writer.write(iSession.current_weight + "");
        }
        /* Close the File */
        file_writer.close();
    }
    private static User_Profile load_profile(String user_file_name) throws IOException{
        User_Profile profile = new User_Profile();
        File user_file = new File(Path + user_file_name);
        FileReader file_reader = new FileReader(user_file);
        Scanner file_scanner = new Scanner(file_reader);
        String [] sxFirstLine = file_scanner.nextLine().split(",");
        /* Get User Name and Pin */
        profile.set_user_name(sxFirstLine[0]);
        profile.set_user_pin(Integer.parseInt(sxFirstLine[1]));
        /* Get Session Count*/
        //String sxsession_count = file_scanner.next();        
        //sxsession_count.replace("\r\n", "");
        int session_count = Integer.parseInt(sxFirstLine[2]);
        String [] sxReadLine;
        /* Write Sessions */
        for (int i = 0; i < session_count; i++){
            workout_session iSession= profile.new_session();
            Scanner line_scanner = new Scanner(file_scanner.nextLine());
            line_scanner.useDelimiter(",");
            /* Read Session Time */
            iSession.session_time = line_scanner.nextDouble();           
            /* Read Distance Run */
            iSession.distance_run = line_scanner.nextDouble();
            /* Write Average Heartrate */
            iSession.heartrate_average = line_scanner.nextDouble();
            /* Write Calories Burned */            
            iSession.calories_burned = line_scanner.nextDouble();
            /* Write Current Weight */           
            iSession.current_weight = line_scanner.nextDouble();
        }
        /* Close the File */
        file_reader.close();
        return profile;
    }
    private int hash (int value){
        return value;
    }
}
